package com.cy.teducommunitys.com.cy.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cy.teducommunitys.com.common.vo.ClienUserVo;
import com.cy.teducommunitys.com.common.vo.JsonResult;
import com.cy.teducommunitys.com.common.vo.UserForManagerVo;
import com.cy.teducommunitys.com.cy.entity.User;
import com.cy.teducommunitys.com.cy.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * <p>
 * 用户详细信息表 前端控制器
 * </p>
 *
 * @author mdzz
 * @since 2019-07-19
 */
@RestController
@RequestMapping("/cy/user/")
@Slf4j
public class UserController {
    @Autowired
    private IUserService iUserService;

    /**根据用户的查询条件name，分页返回数据
     * page中传入的变量为current：当前页码 和 size：每一页多少行
     * */
    @RequestMapping("doSelectUserPage")
    public JsonResult doSelectUserPage(@ModelAttribute Page<UserForManagerVo> page, String username){
        IPage<UserForManagerVo> userIPage = iUserService.selectUserPage(page, username);
        return new JsonResult(userIPage);
    }
    /**新增用户*/
    @RequestMapping("doInsertObject")
    public JsonResult dodoInsertObject(User user){
        iUserService.saveObject(user);
        return new JsonResult("save ok");
    }

    /**修改用户数据*/
    @RequestMapping("doUpdateObject")
    public JsonResult doUpdateObject(User user){
        iUserService.updateObject(user);
        return new JsonResult("update ok");
    }
    /**后台管理删除用户*/
    @RequestMapping("doDeleteObject")
    public JsonResult doDeleteObject(Integer id){
        iUserService.deleteObject(id);
        return new JsonResult("delete ok");
    }
    /**通过userid查询数据*/
    @RequestMapping("doFindObjectById")
    public JsonResult doFindObjectById(Integer userId){
        UserForManagerVo objectById = iUserService.findObjectById(userId);
        return new JsonResult(objectById);
    }
     /** 登录认证
      * TODU:记住密码功能
      * */
    @RequestMapping("doLogin")
    @ResponseBody
    public JsonResult doLogin(String username,String password){
        //1.获取Subject对象
        Subject subject= SecurityUtils.getSubject();
        //2.通过Subject提交用户信息,交给shiro框架进行认证操作
        //2.1对用户进行封装
        UsernamePasswordToken token=
                new UsernamePasswordToken(
                        username,//身份信息
                        password);//凭证信息
        //2.2对用户信息进行身份认证
        subject.login(token);
        //分析:
        //1)token会传给shiro的SecurityManager
        //2)SecurityManager将token传递给认证管理器
        //3)认证管理器会将token传递给realm
        return new JsonResult("login ok");
    }
    /**接受请求处理手机验证并返回结果*/
    @RequestMapping("doGetCode")
    public JsonResult doGetCode(String phone){
        String code = iUserService.getCode(phone);
        return new JsonResult(code);
    }
    /**启用与禁用用户*/
    @RequestMapping("doValidById")
    @ResponseBody
    public JsonResult doValidById(Integer id,Integer valid){
        log.info(id.toString());
        User user = new User();
        user.setUserId(id);
        user.setValid(valid);
        iUserService.validById(user);
        return new JsonResult("update ok");
    }
    /**修改用户密码*/
    @RequestMapping("doUpdatePassword")
    @ResponseBody
    public JsonResult doUpdatePassword(String pwd,String newPwd,String cfgPwd) {
        iUserService.updatePassword(pwd, newPwd, cfgPwd);
        return new JsonResult("update ok");
    }

//    @RequestMapping("doCheckUserName")
//    @ResponseBody
//    public JsonResult doCheckUserName(String name){
//        iUserService.checkUserName(name);
//        return new JsonResult("check ok");
//    }


    /** 检查用户名是否重复 */
    @RequestMapping("doCheckUserName")
    public JsonResult doCheckUserName(String userName){
        System.out.println(this.getClass().getName()+"doCheckUserName");
        return iUserService.checkUserName(userName);
    }
    /** 检查手机是否重复 */
    @RequestMapping("doCheckMobile")
    public JsonResult doCheckMobile(String mobile){
        System.out.println(this.getClass().getName()+"===>doCheckMobile");
        return iUserService.checkMobile(mobile);
    }

    //手机验证码获取
    @RequestMapping("doGetMobileComfirm")
    public JsonResult doGetMobileComfirm(@RequestParam("phone") String phone, HttpSession httpSession){
//        String code = iUserService.getCode(phone);
        System.out.println(this.getClass().getName()+"===>doGetMobileComfirm:"+httpSession);
        System.out.println(this.getClass().getName()+"===>doGetMobileComfirm:"+phone);
        String code = "123456";
        if(code.equals("0000"))
            return new JsonResult(new Throwable("发送短信失败"));

        JSONObject json = new JSONObject();
        json.put("phone",phone);
        json.put("code",code);
        json.put("createTime",System.currentTimeMillis());
        // 将认证码存入SESSION
        httpSession.setAttribute("code",json);
        return new JsonResult("发送短信成功");
    }


    //注册
    @RequestMapping("doRegister")
    JsonResult doRegister(ClienUserVo user, HttpSession httpSession) throws Throwable {
        System.out.println("=======user======="+user);
        System.out.println("=*=*=mobileComfirm*=*=*=>>>"+user.getMobileComfirm());
        //1.检查账号是否已注册
        JsonResult checkUserName = iUserService.checkUserName(user.getUserName());
        if(checkUserName.getState()==0)throw  new Throwable(checkUserName.getMessage());
        //2.检查手机是否已注册
        JsonResult checkMobile = iUserService.checkMobile(user.getMobile());
        if(checkMobile.getState()==0)throw  new Throwable(checkMobile.getMessage());
        //3.检查验证码是否正确
        JSONObject json = (JSONObject) httpSession.getAttribute("code");
        String phone = json.getString("phone");
        String code = json.getString("code");
        System.out.println("phone and code:" + phone +"<===>"+ code);

        if(user.getMobile().equals(phone)&&user.getMobileComfirm().equals(code)){

            user.setCreatedTime(new Date());

            iUserService.saveObject(user);
            return new JsonResult();
        }
        return new JsonResult(new Throwable("注册失败"));
    }




}

